package com.netcracker.ui.command;

import com.netcracker.entity.record.UserRecord;
import com.netcracker.util.service.ServiceFacade;
import com.netcracker.util.service.UserService;
import com.netcracker.util.service.exception.DataTransmittingException;
import com.netcracker.util.service.exception.WrongUserException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;

public class ChangeUserInfoCommand implements Command {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ChangeUserInfoCommand.class);
    private final ServiceFacade serviceFacade;

    public ChangeUserInfoCommand(ServiceFacade serviceFacade) {
        this.serviceFacade = serviceFacade;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
        String currentLogin = (String) request.getSession().getAttribute("user");
        String username = request.getParameter("username");
        if (currentLogin.equals(username)) {
            String fullName = request.getParameter("fullName");
            Integer countryID = Integer.parseInt(request.getParameter("countryID"));
            String date = request.getParameter("bDate");
            UserService userService = serviceFacade.getUserService();
            Date bDate = null;
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); 
            try {
                bDate = formatter.parse(date);
            } catch (ParseException ex) {
                LOGGER.error(ex.getMessage(), ex);
            }
            UserRecord userRecord = new UserRecord();
            userRecord.setLogin(username);
            userRecord.setCountry(countryID);
            userRecord.setFullName(fullName);
            userRecord.setDateOfBirth(bDate);
            try {
                userService.changeUserInfo(userRecord);
                return "UserProfile.jsp";
            } catch (WrongUserException ex) {
                request.setAttribute("error", "Пользователь не найден.");
                return "index.jsp";
            } catch (DataTransmittingException ex) {
                request.setAttribute("error", "Ошибка обращения к БД.");
                LOGGER.error("DB error:", ex);
                return "index.jsp";
            }
        } else {
            request.setAttribute("error", "Недостаточно прав на изменение личной информациии.");
            return "index.jsp";
        }       
    }  
}